<template>
  <div class="statistics-report">
    <SearchForm
      v-model="searchParams"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 统计报表内容 -->
    <el-card class="report-card">
      <div class="report-header">
        <h2 class="report-title">按年级和高校统计表</h2>
        <p class="report-subtitle" :style="isPhone ? { display: 'block' } : {}">
          <div style="margin-right: 20px;">
            <span style="color: #409eff;">人数总计（蓝色）</span>/ <span style="color: #67c23a;">分类小计（绿色）</span>/ <span style="color: black;">明细列（黑色）</span>
          </div>
          <div>
            总人数: <span class="highlight-number">{{ totalCount }}</span>
          </div>
        </p>
      </div>

      <!-- 多维表格 -->
      <div class="table-container" v-loading="loading">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
        >
          <!-- 年级列 -->
          <el-table-column prop="trainYear" label="年级" width="100" align="center">
            <template #default="{ row }">
              <span v-if="row.trainYear === 0" class="total-row">合计</span>
              <span v-else>{{ row.trainYear }}级</span>
            </template>
          </el-table-column>

          <!-- 人数总计列 -->
          <el-table-column prop="total" label="人数总计" width="100" align="center">
            <template #default="{ row }">
              <span class="highlight-number">{{ row.total }}</span>
            </template>
          </el-table-column>

          <!-- 分类小计列组 -->
          <el-table-column label="分类小计" align="center">
            <el-table-column prop="subTotal.fullTimeMastersCount" label="在校硕士" width="100" align="center">
              <template #default="{ row }">
                <span class="green-number">{{ row.subTotal.fullTimeMastersCount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="subTotal.fullTimeDoctorCount" label="在校博士" width="100" align="center" >
              <template #default="{ row }">
                <span class="green-number">{{ row.subTotal.fullTimeDoctorCount }}</span>
              </template> 
            </el-table-column>
            <el-table-column prop="subTotal.onTheJobDoctorCount" label="在职博士" width="100" align="center">
              <template #default="{ row }">
                <span class="green-number">{{ row.subTotal.onTheJobDoctorCount }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 各高校列组 -->
          <el-table-column
            v-for="university in universityList"
            :key="university.value"
            :label="university.label"
            align="center"
          >
            <el-table-column
              :prop="`universityData.${university.value}.fullTimeMastersCount`"
              label="在校硕士"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                {{ getUniversityData(row, university.value, 'fullTimeMastersCount') }}
              </template>
            </el-table-column>
            <el-table-column
              :prop="`universityData.${university.value}.fullTimeDoctorCount`"
              label="在校博士"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                {{ getUniversityData(row, university.value, 'fullTimeDoctorCount') }}
              </template>
            </el-table-column>
            <el-table-column
              :prop="`universityData.${university.value}.onTheJobDoctorCount`"
              label="在职博士"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                {{ getUniversityData(row, university.value, 'onTheJobDoctorCount') }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from "vue";
import SearchForm from "./searchForm.vue";
import { getTrainYearUniversityStatistics } from "@/api/statistics";
import { ElMessage } from "element-plus";
import { isPhone } from "@/utils/index";

const { proxy } = getCurrentInstance();

// 搜索参数
const searchParams = ref({});

// 统计数据
const tableData = ref([]);
const loading = ref(false);

// 获取字典数据
const { university } = proxy.useDict("university");

// 计算总人数
const totalCount = computed(() => {
  if (tableData.value.length === 0) return 0;
  const totalRow = tableData.value.find(row => row.trainYear === 0);
  return totalRow ? totalRow.total : 0;
});

// 获取所有高校列表
const universityList = computed(() => {
  if (!university.value || university.value.length === 0) return [];
  return university.value;
});

// 获取高校数据
const getUniversityData = (row, universityKey, field) => {
  if (!row.universityData || !row.universityData[universityKey]) {
    return 0;
  }
  return row.universityData[universityKey][field] || 0;
};

// 表头样式函数
const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  // 基础样式
  const baseStyle = {
    background: '#f5f7fa',
    color: '#606266'
  };
  
  // 分类小计列（第3-5列：在校硕士、在校博士、在职博士）
  if (columnIndex >= 2 && columnIndex <= 4) {
    return {
      ...baseStyle,
      background: '#67c23a',
      color: '#fff',
      fontWeight: 'bold'
    };
  }
  
  return baseStyle;
};

// 单元格样式函数
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  // 分类小计列（第3-5列）设置浅绿色背景
  if (columnIndex >= 2 && columnIndex <= 4) {
    return {
      background: '#f0f9ff',
      fontWeight: '600'
    };
  }
  return {};
};

// 处理表格数据
const processTableData = (data) => {
  if (!data || data.length === 0) return [];
  
  return data.map(item => {
    // 构建高校数据映射
    const universityData = {};
    if (item.universityTotalList && item.universityTotalList.length > 0) {
      item.universityTotalList.forEach(uni => {
        universityData[uni.trainUniversity] = {
          fullTimeMastersCount: uni.fullTimeMastersCount || 0,
          fullTimeDoctorCount: uni.fullTimeDoctorCount || 0,
          onTheJobDoctorCount: uni.onTheJobDoctorCount || 0,
          totalCount: uni.totalCount || 0
        };
      });
    }
    
    return {
      trainYear: item.trainYear,
      total: item.total || 0,
      subTotal: item.subTotal || {
        fullTimeMastersCount: 0,
        fullTimeDoctorCount: 0,
        onTheJobDoctorCount: 0,
        totalCount: 0
      },
      universityData
    };
  });
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    loading.value = true;
    
    const res = await getTrainYearUniversityStatistics(searchParams.value);
    if (res.code === 200) {
      tableData.value = processTableData(res.data);
    } else {
      ElMessage.error(res.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
    ElMessage.error("加载统计数据失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  console.log("搜索参数:", searchParams.value);
  loadStatistics();
};

// 重置处理
const handleReset = () => {
  console.log("重置搜索");
  loadStatistics();
};

// 组件挂载时加载数据
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
.statistics-report {
  padding: 20px;
}

.report-card {
  margin-top: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.report-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.report-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
  display: flex;
}

.highlight-number {
  color: #409eff;
  font-weight: bold;
  font-size: 1.2em;
}

.green-number {
  color: #67c23a;
  font-weight: bold;
  font-size: 1.2em;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.total-row {
  font-weight: bold;
  color: #303133;
  background-color: #f5f7fa;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600;
  text-align: center;
}

:deep(.el-table td) {
  text-align: center;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table--border th) {
  border-right: 1px solid #ebeef5;
}

/* 合计行样式 */
:deep(.el-table__body tr:last-child td) {
  background-color: #f5f7fa !important;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .table-container {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .statistics-report {
    padding: 10px;
  }

  .report-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .report-title {
    font-size: 20px;
  }

  .report-subtitle {
    font-size: 14px;
  }

  .table-container {
    font-size: 12px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .report-title {
    font-size: 18px;
  }

  .table-container {
    font-size: 11px;
  }

  :deep(.el-table) {
    font-size: 11px;
  }
}
</style>